import uuid
from datetime import datetime

from seat_manager import get_available_seats, generate_all_seats


def check_seat_availability(target_date, target_timeslot, seat_id, all_reservations):
    for reservation in all_reservations:
        if (reservation["date"] == target_date and
                reservation["timeslot"] == target_timeslot and
                reservation["seat_id"] == seat_id):
            return False
    return True


def check_user_booking_limit(student_id, target_date, target_timeslot, all_reservations):
    for reservation in all_reservations:
        if (reservation["student_id"] == student_id and
                reservation["date"] == target_date and
                reservation["timeslot"] == target_timeslot):
            return False
    return True


def create_reservation_object(student_id, target_date, target_timeslot, seat_id):
    return {
        "reservation_id": str(uuid.uuid4()),
        "student_id": student_id,
        "date": target_date,
        "timeslot": target_timeslot,
        "seat_id": seat_id
    }


def make_reservation_interaction(all_reservations, layout_info):
    print("\n=== 预约座位 ===")

    # 获取学号
    student_id = input("请输入学号: ").strip()
    if not student_id:
        print("学号不能为空。")
        return None

    # 获取日期 + 新增：校验日期有效性（不能早于当前日期）
    while True:
        date_str = input("请输入日期 (YYYY-MM-DD): ")
        try:
            input_date = datetime.strptime(date_str, "%Y-%m-%d")
            # 核心：检查是否为过去日期
            if input_date < datetime.now():
                print("不能预约过去的日期，请重新输入。")
                continue
            break
        except ValueError:
            print("日期格式无效，请重新输入。")

    # 获取时段
    print("\n可选时段:")
    for i, timeslot in enumerate(layout_info["timeslots"], 1):
        print(f"{i}. {timeslot}")

    while True:
        try:
            choice = int(input("请选择时段 (1-3): "))
            if 1 <= choice <= len(layout_info["timeslots"]):
                timeslot = layout_info["timeslots"][choice - 1]
                break
            else:
                print("无效的选择，请重新输入。")
        except ValueError:
            print("请输入有效的数字。")

    # 检查用户是否已预约该时段
    if not check_user_booking_limit(student_id, date_str, timeslot, all_reservations):
        print(f"您已经在 {date_str} {timeslot} 预约了其他座位。")
        return None

    # 获取可用座位
    available_seats, _ = get_available_seats(date_str, timeslot, all_reservations, layout_info)
    print("\n可用座位:")
    if available_seats:
        for i in range(0, len(available_seats), 10):
            row = available_seats[i:i+10]
            print(" ".join(row))
    else:
        print("无可用座位")

    # 获取座位号并校验
    seat_id = input("请输入座位号 (如 A01): ").strip().upper()
    all_seats = generate_all_seats(layout_info)
    if seat_id not in all_seats:
        print("无效的座位号。")
        return None
    if not check_seat_availability(date_str, timeslot, seat_id, all_reservations):
        print("该座位已被预约。")
        return None

    # 创建预约
    reservation = create_reservation_object(student_id, date_str, timeslot, seat_id)
    print(f"\n预约成功! 座位 {seat_id} 已在 {date_str} {timeslot} 为您预留。")
    return reservation



def find_reservation_to_cancel(student_id, target_date, target_timeslot, seat_id, all_reservations):
    for reservation in all_reservations:
        if (reservation["student_id"] == student_id and
                reservation["date"] == target_date and
                reservation["timeslot"] == target_timeslot and
                reservation["seat_id"] == seat_id):
            return reservation
    return None


def cancel_reservation_interaction(all_reservations, layout_info=None):
    print("\n=== 取消预约 ===")

    # Get student ID
    student_id = input("请输入学号: ").strip()
    if not student_id:
        print("学号不能为空。")
        return all_reservations

    # Get date
    while True:
        date_str = input("请输入预约日期 (YYYY-MM-DD): ")
        try:
            datetime.strptime(date_str, "%Y-%m-%d")
            break
        except ValueError:
            print("日期格式无效，请重新输入。")

    # Get timeslot
    print("\n可选时段:")
    for i, timeslot in enumerate(layout_info["timeslots"], 1):
        print(f"{i}. {timeslot}")

    while True:
        try:
            choice = int(input("请选择时段 (1-3): "))
            if 1 <= choice <= len(layout_info["timeslots"]):
                timeslot = layout_info["timeslots"][choice - 1]
                break
            else:
                print("无效的选择，请重新输入。")
        except ValueError:
            print("请输入有效的数字。")

    # Get seat ID
    seat_id = input("请输入座位号 (如 A01): ").strip().upper()

    # Find and cancel reservation
    reservation = find_reservation_to_cancel(student_id, date_str, timeslot, seat_id, all_reservations)
    if reservation:
        all_reservations.remove(reservation)
        print(f"\n已成功取消 {date_str} {timeslot} 座位 {seat_id} 的预约。")
        return all_reservations
    else:
        print("未找到匹配的预约记录。")
        return all_reservations


def get_my_reservations(student_id, all_reservations):
    my_reservations = [r for r in all_reservations if r["student_id"] == student_id]

    # 简单按日期和时间排序（假设时间段的顺序是固定的）
    my_reservations.sort(key=lambda x: (x["date"], x["timeslot"]))

    return my_reservations


def format_reservation_for_display(reservation_dict):
    return (f"日期: {reservation_dict['date']} | "
            f"时段: {reservation_dict['timeslot']} | "
            f"座位: {reservation_dict['seat_id']} | "
            f"预约ID: {reservation_dict['reservation_id']}")


def view_my_reservations_interaction(all_reservations):
    print("\n=== 我的预约 ===")

    # Get student ID
    student_id = input("请输入学号: ").strip()
    if not student_id:
        print("学号不能为空。")
        return

    # Get and display reservations
    my_reservations = get_my_reservations(student_id, all_reservations)

    if not my_reservations:
        print("您当前没有预约记录。")
    else:
        print("\n您的预约记录:")
        for i, reservation in enumerate(my_reservations, 1):
            print(f"{i}. {format_reservation_for_display(reservation)}")